//获取应用实例  
var app = getApp();

//引入这个插件，使html内容自动转换成wxml内容
var WxParse = require('../../../wxParse/wxParse.js');
var order=["goods_d","goods_p","goods_pj"];
Page({
  data: {
    host: app.d.hostImg,
    flag: 1,
    All: [],
    Medium: [],
    Good: [],
    Bad: [],
    bannerApp: true,
    winWidth: 0,
    winHeight: 0,
    currentTab: 0, //tab切换  
    pro_id: 0,
    itemData: {},
    bannerItem: [],
    buynum: 1,
    // 产品图片轮播
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 1000,
    attrValueList: [],
    buff: '',
    //toView: "goods_d",
    yjqflag: true,
    act_modal_list:'',
    dixy:'none',
    shareimg:'',
    poster:'' ,
    name: '',
    author: '',
    src: 0,
    mp4:0,
    groups:[],
  },
  // 传值
  onLoad: function(option) {
    console.log(option)
    var that = this;
    that.setData({
      pro_id:option.pro_id
    });
    that.initNavHeight();
    that.loadgroups();
    setTimeout(function() {
      console.log(app.globalData.userInfo)
      if (app.globalData.userInfo == null) {
        console.log("未登录")
        console.log(option.DATA)
        if (typeof option.DATA != 'undefined') {
          //分享
          var DAta = option.DATA
          wx.showModal({
            title: '请先登录',
            content: '登录获取更多信息',
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '../user/user?DAta=' + DAta,
                })
              }
            }
          })
        } else if (typeof option.pro_id != 'undefined') {
          wx.showModal({
            title: '请先登录',
            content: '登录获取更多信息',
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                wx.redirectTo({
                  url: '../user/user?pro_id=' + option.pro_id,
                })
              }
            }
          })
        } else {
          //不是分享
          wx.showModal({
            title: '请先登录',
            content: '登录获取更多信息',
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                //如果从BtoB进，去BtoB登录
                if (app.globalData.froms == 'company_user') {
                  wx.switchTab({
                    url: '../company_user/company_user',
                  })
                } else {
                  //如果从BtoC进，去BtoC登录
                  wx.redirectTo({
                    url: '../user/user',
                  })
                }
              }
            }
          })
        }
      } else {
        //登陆过
        // console.log(app.globalData.froms)
        // if (app.globalData.froms == 'company_user') {
        //   wx.setNavigationBarColor({
        //     frontColor: 'white',
        //     backgroundColor: '#e93d3b',
        //   })
        // } else {
        //   wx.setNavigationBarColor({
        //     frontColor: 'white',
        //     backgroundColor: '#e93d3b',
        //   })
        // }
        if ((typeof option.DATA) != 'undefined') {
          that.setData({
            DAta: option.DATA
          })
          var DAta = option.DATA.split(",")
          console.log(DAta[0] + ',' + DAta[1] + ',' + DAta[2])
          that.setData({
            bindUid: DAta[0],
            pro_id: DAta[1],
            store_id: DAta[2]
          })
        } else {
          that.setData({
            pro_id: option.pro_id,
            uid: app.d.userId,
          });
        }
        if (option.pro_id) {
          pro_id: option.pro_id
        }
        that.loadProductDetail();
        console.log("详情已加载")
        that.loadProductEvaluate();
        console.log("评论已加载")
      }
    }, 500)
  },
  // 立即购买弹窗
  setModalStatus: function(e) {
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step();
    this.setData({
      animationData: animation.export()
    })
    if (e.currentTarget.dataset.status == 1) {
      this.setData({
        showModalStatus: true,
        buynum: 1
      });
    }

    //当规格数据存在时执行  true
    if (this.data.HAVE) {
      setTimeout(function() {
        animation.translateY(0).step()
        this.setData({
          animationData: animation
        })
        if (e.currentTarget.dataset.status == 0) {
          this.setData({
            showModalStatus: false,
            attrValueList: [],
            buynum: 1
          });
        }
      }.bind(this), 200)
      this.setData({
        includeGroup: this.data.commodityAttr,
        totalPrice: this.data.itemData.price_yh * this.data.buynum
      });
      this.distachAttrValue(this.data.commodityAttr);
      if (this.data.commodityAttr.length == 1) {
        for (var i = 0; i < this.data.commodityAttr[0].attrValueList.length; i++) {
          this.data.attrValueList[i].selectedValue = this.data.commodityAttr[0].attrValueList[i].attrValue;
        }
        this.setData({
          attrValueList: this.data.attrValueList
        });
      }
    } else {
      //当规格数据不存在时
      setTimeout(function() {
        animation.translateY(0).step()
        this.setData({
          animationData: animation
        })
        if (e.currentTarget.dataset.status == 0) {
          this.setData({
            showModalStatus: false,
            buynum: 1
          });
        }
      }.bind(this), 200)
      this.setData({
        totalPrice: this.data.itemData.price_yh * this.data.buynum
      });
    }
  },
  // 加入购物车弹窗
  setModalStatu: function(e) {
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step();
    this.setData({
      animationData: animation.export()
    })
    if (e.currentTarget.dataset.status == 1) {
      this.setData({
        showModalStatu: true,
        buynum: 1
      });
    }
    if (this.data.HAVE) {
      setTimeout(function() {
        animation.translateY(0).step()
        this.setData({
          animationData: animation
        })
        if (e.currentTarget.dataset.status == 0) {
          this.setData({
            showModalStatu: false,
            attrValueList: [],
            buynum: 1
          });
        }
      }.bind(this), 200)
      this.setData({
        includeGroup: this.data.commodityAttr,
        totalPrice: this.data.itemData.price_yh * this.data.buynum
      });
      this.distachAttrValue(this.data.commodityAttr);
      if (this.data.commodityAttr.length == 1) {
        for (var i = 0; i < this.data.commodityAttr[0].attrValueList.length; i++) {
          this.data.attrValueList[i].selectedValue = this.data.commodityAttr[0].attrValueList[i].attrValue;
        }
        this.setData({
          attrValueList: this.data.attrValueList
        });
      }
    } else {
      setTimeout(function() {
        animation.translateY(0).step()
        this.setData({
          animationData: animation
        })
        if (e.currentTarget.dataset.status == 0) {
          this.setData({
            showModalStatu: false,
            buynum: 1
          });
        }
      }.bind(this), 200)
      this.setData({
        totalPrice: this.data.itemData.price_yh * this.data.buynum
      });
    }
  },

  // 加减
  changeNum: function(e) {
    var that = this;
    if (e.target.dataset.alphaBeta == 0) {
      if (this.data.buynum <= 1) {
        buynum: 1
      }
      else {
        this.setData({
          buynum: this.data.buynum - 1
        })
      };
    } else {
      this.setData({
        buynum: this.data.buynum + 1
      })
    };
    this.count()
  },
  // 商品详情数据获取
  loadProductDetail: function() {
    var that = this;
    wx.request({
      url: app.d.ceshiUrl + '/Api/GroupProduct/index',
      method: 'post',
      data: {
        store_id: that.data.store_id,
        pro_id: that.data.pro_id,
        r_uid: app.d.userId,
        u_id: that.data.bindUid,
      },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        console.log(res)
        var status = res.data.status;
        if (status == 1) {
          var pro = res.data.pro;
          var content = pro.content;
          console.log(content);
          WxParse.wxParse('content', 'html', content, that, 1);
          that.setData({
            itemData: pro,
            bannerItem: pro.img_arr,
            collect: res.data.pro.collect,
            store_id: res.data.pro.store_id,
            poster:pro.photo_x,
            name: pro.name,
            author: pro.store_name,
            src: pro.audio,
            mp4:pro.mp4,

          })
          if (res.data.commodityAttr != null) {
            that.setData({
              commodityAttr: res.data.commodityAttr,
              HAVE: true
            })
          } else {
            that.setData({
              HAVE: false
            })
          }
        } else {
          console.log(status)
          wx.showToast({
            title: res.data.err,
            duration: 2000,
          });
        }
      },
      error: function(e) {
        wx.showToast({
          title: '网络不给力！',
          duration: 2000,
        });
      },
    });
  },
  //商品评价数据获取
  loadProductEvaluate: function() {
    var that = this;
    wx.request({
      url: app.d.ceshiUrl + '/Api/Comment/comment_show',
      method: 'post',
      data: {
        pid: that.data.pro_id,
        flag:1,
      },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        if (res.data.product_dp.length != 0) {
          that.setData({
            All: (typeof(res.data.product_dp.all) != 'undefined' ? res.data.product_dp.all : []),
            Good: (typeof(res.data.product_dp.good) != 'undefined' ? res.data.product_dp.good : []),
            Medium: (typeof(res.data.product_dp.medium) != 'undefined' ? res.data.product_dp.medium : []),
            Bad: (typeof(res.data.product_dp.bad) != 'undefined' ? res.data.product_dp.bad : [])
          })

          function checkTime(num) {
            if (num < 10) {
              num = "0" + num
            }
            return num
          }
          if (that.data.All.length != 0) {
            that.setData({
              all: []
            })
            for (var i = 0; i < that.data.All.length; i++) {
              var dateTime = new Date(that.data.All[i].addtime * 1000)
              that.setData({
                time: dateTime.getFullYear() + '.' + (dateTime.getMonth() + 1) + '.' + dateTime.getDate() + '  ' + checkTime(dateTime.getHours()) + ':' + checkTime(dateTime.getMinutes()),
              })
              that.setData({
                all: that.data.all.concat({
                  time: that.data.time
                })
              })
            }
          }
          if (that.data.Good.length != 0) {
            that.setData({
              good: []
            })
            for (var i = 0; i < that.data.Good.length; i++) {
              var dateTime = new Date(that.data.Good[i].addtime * 1000)
              that.setData({
                time: dateTime.getFullYear() + '.' + (dateTime.getMonth() + 1) + '.' + dateTime.getDate() + '  ' + checkTime(dateTime.getHours()) + ':' + checkTime(dateTime.getMinutes()),
              })
              that.setData({
                good: that.data.good.concat({
                  time: that.data.time
                })
              })
            }
          }
          if (that.data.Medium.length != 0) {
            that.setData({
              medium: []
            })
            for (var i = 0; i < that.data.Medium.length; i++) {
              var dateTime = new Date(that.data.Medium[i].addtime * 1000)
              that.setData({
                time: dateTime.getFullYear() + '.' + (dateTime.getMonth() + 1) + '.' + dateTime.getDate() + '  ' + checkTime(dateTime.getHours()) + ':' + checkTime(dateTime.getMinutes()),
              })
              that.setData({
                medium: that.data.medium.concat({
                  time: that.data.time
                })
              })
            }
          }
          if (that.data.Bad.length != 0) {
            that.setData({
              bad: []
            })
            for (var i = 0; i < that.data.Bad.length; i++) {
              var dateTime = new Date(that.data.Bad[i].addtime * 1000)
              that.setData({
                time: dateTime.getFullYear() + '.' + (dateTime.getMonth() + 1) + '.' + dateTime.getDate() + '  ' + checkTime(dateTime.getHours()) + ':' + checkTime(dateTime.getMinutes()),
              })
              that.setData({
                bad: that.data.bad.concat({
                  time: that.data.time
                })
              })
            }
          }
        } else {
          that.setData({
            All: [],
            Good: [],
            Medium: [],
            Bad: []
          })
        }

      },
      error: function(e) {
        wx.showToast({
          title: '网络不给力！',
          duration: 2000,
        });
      },
    });
  },
  getFlag: function(e) {
    console.log(e)
    var ID = e.currentTarget.id
    if (ID == 1) {
      this.setData({
        flag: 1
      })
    }
    if (ID == 2) {
      this.setData({
        flag: 2
      })
    }
    if (ID == 3) {
      this.setData({
        flag: 3
      })
    }
    if (ID == 4) {
      this.setData({
        flag: 4
      })
    }

  },
  // 属性选择
  onShow: function() {

  },
  /* 获取数据 */
  distachAttrValue: function(commodityAttr) {
    /** 
    将后台返回的数据组合成类似 
    { 
    attrKey:'型号', 
    attrValueList:['1','2','3'] 
    } 
    */
    // 把数据对象的数据（视图使用），写到局部内 
    var attrValueList = this.data.attrValueList;
    // 遍历获取的数据 
    for (var i = 0; i < commodityAttr.length; i++) {
      for (var j = 0; j < commodityAttr[i].attrValueList.length; j++) {
        var attrIndex = this.getAttrIndex(commodityAttr[i].attrValueList[j].attrKey, attrValueList);
        // console.log('属性索引', attrIndex); 
        // 如果还没有属性索引为-1，此时新增属性并设置属性值数组的第一个值；索引大于等于0，表示已存在的属性名的位置 
        if (attrIndex >= 0) {
          // 如果属性值数组中没有该值，push新值；否则不处理 
          if (!this.isValueExist(commodityAttr[i].attrValueList[j].attrValue, attrValueList[attrIndex].attrValues)) {
            attrValueList[attrIndex].attrValues.push(commodityAttr[i].attrValueList[j].attrValue);
          }
        } else {
          attrValueList.push({
            attrKey: commodityAttr[i].attrValueList[j].attrKey,
            attrValues: [commodityAttr[i].attrValueList[j].attrValue]
          });
        }
      }
    }
    // console.log('result', attrValueList) 
    for (var i = 0; i < attrValueList.length; i++) {
      for (var j = 0; j < attrValueList[i].attrValues.length; j++) {
        if (attrValueList[i].attrValueStatus) {
          attrValueList[i].attrValueStatus[j] = true;
        } else {
          attrValueList[i].attrValueStatus = [];
          attrValueList[i].attrValueStatus[j] = true;
        }
      }
    }
    this.setData({
      attrValueList: attrValueList
    });
  },
  getAttrIndex: function(attrName, attrValueList) {
    // 判断数组中的attrKey是否有该属性值 
    for (var i = 0; i < attrValueList.length; i++) {
      if (attrName == attrValueList[i].attrKey) {
        break;
      }
    }
    return i < attrValueList.length ? i : -1;
  },
  isValueExist: function(value, valueArr) {
    // 判断是否已有属性值 
    for (var i = 0; i < valueArr.length; i++) {
      if (valueArr[i] == value) {
        break;
      }
    }
    return i < valueArr.length;
  },
  /* 选择属性值事件 */
  selectAttrValue: function(e) {
    /* 
    点选属性值，联动判断其他属性值是否可选 
    { 
    attrKey:'型号', 
    attrValueList:['1','2','3'], 
    selectedValue:'1', 
    attrValueStatus:[true,true,true] 
    } 
    console.log(e.currentTarget.dataset); 
    */
    var attrValueList = this.data.attrValueList;
    var index = e.currentTarget.dataset.index; //属性索引 
    var key = e.currentTarget.dataset.key;
    var price = e.currentTarget.dataset.price;
    var id = e.currentTarget.dataset.id;
    var value = e.currentTarget.dataset.value;
    if (e.currentTarget.dataset.status || index == this.data.firstIndex) {
      if (e.currentTarget.dataset.selectedvalue == e.currentTarget.dataset.value) {
        // 取消选中 
        this.disSelectValue(attrValueList, index, key, value);
      } else {
        // 选中 
        this.selectValue(attrValueList, index, key, value);
      }
    }
  },
  /* 选中 */
  selectValue: function(attrValueList, index, key, value, unselectStatus) {
    // console.log('firstIndex', this.data.firstIndex); 
    var includeGroup = [];
    if (index == this.data.firstIndex && !unselectStatus) { // 如果是第一个选中的属性值，则该属性所有值可选 
      var commodityAttr = this.data.commodityAttr;
      // 其他选中的属性值全都置空 
      // console.log('其他选中的属性值全都置空', index, this.data.firstIndex, !unselectStatus); 
      for (var i = 0; i < attrValueList.length; i++) {
        for (var j = 0; j < attrValueList[i].attrValues.length; j++) {
          attrValueList[i].selectedValue = '';
        }
      }
    } else {
      var commodityAttr = this.data.includeGroup;
    }

    // console.log('选中', commodityAttr, index, key, value); 
    for (var i = 0; i < commodityAttr.length; i++) {
      for (var j = 0; j < commodityAttr[i].attrValueList.length; j++) {
        if (commodityAttr[i].attrValueList[j].attrKey == key && commodityAttr[i].attrValueList[j].attrValue == value) {
          includeGroup.push(commodityAttr[i]);
        }
      }
    }
    attrValueList[index].selectedValue = value;


    // 判断属性是否可选 
    for (var i = 0; i < attrValueList.length; i++) {
      for (var j = 0; j < attrValueList[i].attrValues.length; j++) {
        attrValueList[i].attrValueStatus[j] = false;
      }
    }
    for (var k = 0; k < attrValueList.length; k++) {
      for (var i = 0; i < includeGroup.length; i++) {
        for (var j = 0; j < includeGroup[i].attrValueList.length; j++) {
          if (attrValueList[k].attrKey == includeGroup[i].attrValueList[j].attrKey) {
            for (var m = 0; m < attrValueList[k].attrValues.length; m++) {
              if (attrValueList[k].attrValues[m] == includeGroup[i].attrValueList[j].attrValue) {
                attrValueList[k].attrValueStatus[m] = true;
              }
            }
          }
        }
      }
    }
    // console.log('结果', attrValueList); 
    this.setData({
      attrValueList: attrValueList,
      includeGroup: includeGroup
    });

    var count = 0;
    for (var i = 0; i < attrValueList.length; i++) {
      for (var j = 0; j < attrValueList[i].attrValues.length; j++) {
        if (attrValueList[i].selectedValue) {
          count++;
          break;
        }
      }
    }
    if (count < 2) { // 第一次选中，同属性的值都可选 
      this.setData({
        firstIndex: index
      });
    } else {
      this.setData({
        firstIndex: -1
      });
    }
    this.count()

  },
  /* 取消选中 */
  disSelectValue: function(attrValueList, index, key, value) {
    var commodityAttr = this.data.commodityAttr;
    attrValueList[index].selectedValue = '';

    // 判断属性是否可选 
    for (var i = 0; i < attrValueList.length; i++) {
      for (var j = 0; j < attrValueList[i].attrValues.length; j++) {
        attrValueList[i].attrValueStatus[j] = true;
      }
    }
    this.setData({
      includeGroup: commodityAttr,
      attrValueList: attrValueList
    });

    for (var i = 0; i < attrValueList.length; i++) {
      if (attrValueList[i].selectedValue) {
        this.selectValue(attrValueList, i, attrValueList[i].attrKey, attrValueList[i].selectedValue, true);
      }
    }

    this.count()
  },

  initProductData: function(data) {
    data["LunBoProductImageUrl"] = [];
    var imgs = data.LunBoProductImage.split(';');
    for (let url of imgs) {
      url && data["LunBoProductImageUrl"].push(app.d.hostImg + url);
    }
    data.Price = data.Price / 100;
    data.VedioImagePath = app.d.hostVideo + '/' + data.VedioImagePath;
    data.videoPath = app.d.hostVideo + '/' + data.videoPath;
  },

  //添加到收藏
  addFavorites: function(e) {
    var that = this;
    if (this.data.collect == 0) {
      this.setData({
        collect: 1
      })
    } else {
      this.setData({
        collect: 0
      })
    }
    wx.request({
      url: app.d.ceshiUrl + '/Api/Product/colGroup',
      method: 'post',
      data: {
        uid: app.d.userId,
        pid: that.data.pro_id,
      },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        var data = res.data;
        if (data.status == 1) {
          wx.showToast({
            title: res.data.err,
            duration: 2000
          });
          that.data.itemData.isCollect = true;
        } else {
          wx.showToast({
            title: res.data.err,
            duration: 2000
          });
        }
      },
      fail: function() {
        wx.showToast({
          title: '网络不给力！',
          duration: 2000
        });
      }
    });
  },
  addShopCart: function(e) { //添加到购物车
    var that = this;
    var ptype = e.currentTarget.dataset.type;
    //当存在规格数据时
    if (this.data.HAVE) {
      this.setData({
        buff: ''
      })
      for (var i = 0; i < this.data.includeGroup[0].attrValueList.length; i++) {
        if (i != this.data.includeGroup[0].attrValueList.length - 1) {
          this.setData({
            buff: this.data.buff + this.data.includeGroup[0].attrValueList[i].id + ','
          })
        } else {
          console.log(this.data.includeGroup[0].attrValueList[i].id)
          this.setData({
            buff: this.data.buff + this.data.includeGroup[0].attrValueList[i].id
          })
        }
      }
      var value = [];
      for (var i = 0; i < this.data.attrValueList.length; i++) {
        if (!this.data.attrValueList[i].selectedValue) {
          break;
        }
        value.push(this.data.attrValueList[i].selectedValue);
      }
      if (i < this.data.attrValueList.length) {
        wx.showToast({
          title: '请选择完整！',
          icon: 'loading',
          duration: 1000
        })
      } else {
        that.setData({
          tids: []
        })
        for (var i = 0; i < that.data.includeGroup[0].attrValueList.length; i++) {
          console.log("www" + i)
          if (that.data.includeGroup[0].attrValueList[i].tid) {
            that.setData({
              tids: that.data.tids.concat(that.data.includeGroup[0].attrValueList[i].tid)
            })
            console.log("qqq" + that.data.tids)
          }
        }
        wx.request({
          url: app.d.ceshiUrl + '/Api/Shopping/addGroup',
          method: 'post',
          data: {
            uid: app.d.userId,
            pid: that.data.pro_id,
            num: that.data.buynum,
            buff: that.data.buff,
            tid: that.data.tids,
            liji: 1,
            type: (ptype == 'buynow' ? 'buy' : '')
          },
          header: {
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          success: function(res) {
            var data = res.data;
            if (data.status == 1) {
              var DATAs = that.data.buff + ',' + data.cart_id
              if (ptype == 'buynow') {
                wx.navigateTo({
                  url: '/pages/order/pay?DATAs=' + DATAs+'&group_flag=1'
                });
                return;
              } else {
                wx.navigateTo({
                  url: '/pages/order/pay?DATAs=' + DATAs+'&group_flag=3'
                });
                return;
              }
            } else {
              wx.showToast({
                title: data.err,
                duration: 2000
              });
            }
          },
          fail: function() {
            wx.showToast({
              title: '网络不给力！',
              duration: 2000
            });
          }
        });
      }
    } else {
      //当不存在规格数据时
      wx.request({
        url: app.d.ceshiUrl + '/Api/Shopping/addGroup',
        method: 'post',
        data: {
          uid: app.d.userId,
          pid: that.data.pro_id,
          num: that.data.buynum,
          liji: 1,
          type: (ptype == 'buynow' ? 'buy' : '')
        },
        header: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        success: function(res) {
            var data = res.data;
          if (data.status == 1) {
            if (ptype == 'buynow') {
              wx.redirectTo({
                url: '/pages/order/pay?cartId=' + res.data.cart_id+'&group_flag=1'
              });
              return;
            } else {
              wx.redirectTo({
                url: '/pages/order/pay?cartId=' + res.data.cart_id+'&group_flag=3'
              });
              return;
            }
          } else {
            wx.showToast({
              title: data.err,
              duration: 2000
            });
          }
        },
        fail: function() {
          wx.showToast({
            title: '网络不给力！',
            duration: 2000
          });
        }
      });
    }
  },
  bindChange: function(e) { //滑动切换tab 
    var that = this;
    that.setData({
      currentTab: e.detail.current
    });
  },
  initNavHeight: function() { ////获取系统信息
    var that = this;
    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          winWidth: res.windowWidth,
          winHeight: res.windowHeight
        });
      }
    });
  },
  bannerClosed: function() {
    this.setData({
      bannerApp: false,
    })
  },
  swichNav: function(e) { //点击tab切换
    var that = this;
    if (that.data.currentTab === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentTab: e.target.dataset.current
      })
    }
  },
  call: function () {
    wx.makePhoneCall({
      phoneNumber: '' + this.data.itemData.tel_id,
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { },
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(res) {
    var DATA = '' + app.d.userId + ',' + this.data.pro_id + ',' + this.data.store_id
    console.log(DATA)
    if (res.from === 'button') {
      return {
        title: '' + this.data.itemData.name,
        // path: '/pages/product/detail?DATA=' + DATA,
        path: '/pages/FirstPage/FirstPage?store_Id=' + this.data.store_id+"&f_uid=" + app.d.userId+"&pro_id=" + this.data.pro_id,
        imageUrl: '' + this.data.itemData.photo_x,
        success: function(res) {
          // 转发成功
        },
        fail: function(res) {
          // 转发失败
        }
      }
    } else {
      return {
        title: '' + this.data.itemData.name,
        // path: '/pages/product/detail?DATA=' + DATA,
        path: '/pages/FirstPage/FirstPage?store_Id=' + this.data.store_id+"&f_uid=" + app.d.userId+"&pro_id=" + this.data.pro_id,
        imageUrl: '' + this.data.itemData.photo_x,
        success: function(res) {
          // 转发成功
        },
        fail: function(res) {
          // 转发失败
        }
      }
    }
  },
  toBtoC: function() {
    wx.redirectTo({
      url: '/pages/purchase/index?store_Id=' + this.data.store_id,
    })
    app.d.store_Id = this.data.store_id;
  },
  count: function() {
    if (!this.data.HAVE) {
      this.setData({
        totalPrice: (parseFloat(this.data.itemData.price_yh) * this.data.buynum).toFixed(2)
      })

    } else {
      this.setData({
        totalPrice: (parseFloat(this.data.itemData.price_yh) + parseFloat(this.data.includeGroup[0].price)) * this.data.buynum
      })
    }
    console.log(this.data.totalPrice);
    // if (this.data.includeGroup.length == this.data.commodityAttr.length) {
    //   this.setData({
    //     totalPrice: this.data.itemData.price_yh * this.data.buynum
    //   })
    // } else {
    //   this.setData({
    //     totalPrice: (parseFloat(this.data.itemData.price_yh) + parseFloat(this.data.includeGroup[0].price)) * this.data.buynum
    //   })
    // }
  },
  // 预览图片
  previewImg:function(e){
    console.log(e.currentTarget.dataset.index);
    var index = e.currentTarget.dataset.index;
    var imgArr = this.data.bannerItem;
    wx.previewImage({
      current: imgArr[index],     //当前图片地址
      urls: imgArr,               //所有要预览的图片的地址集合 数组形式
      success: function(res) {},
      fail: function(res) {},
      complete: function(res) {},
    })
  },
  getMore: function (e) {
       wx.showToast({
            title: '没有更多数据！',
            duration: 2000
          });
  },
  taps1: function(e) {
    this.setData({
      toView:order[0]
    })
      console.log(order[0])
  },
  taps2: function(e) {
    this.setData({
      toView:order[1]
    })
      console.log(order[1])
  },
  taps3: function(e) {
    this.setData({
      toView:order[2]
    })
      console.log(order[2])
  },
  closeActModal: function() {
        this.setData({
            act_modal_list:'a',
            dixy:'none'
        })
  },
  fenxiang: function() {
     var that =this;
           wx.request({
        url: app.d.ceshiUrl + '/Api/Bshare/index',
        method: 'post',
        data: {
          uid: app.d.userId,
          pid: that.data.pro_id,
          store_id: that.data.store_id,
        },
        header: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        success: function(res) {
            var data = res.data;
          that.setData({
            act_modal_list:'show',
            dixy:'true',
            shareimg:data.img
          })
        },
        fail: function() {
          wx.showToast({
            title: '网络不给力！',
            duration: 2000
          });
        }
      });

  },
  onSavePicClick: function (e) {
    var that=this; 
    console.log("onSavePicClick");
    console.log(e);
    var downloadUrl = e.currentTarget.dataset.img ;
    console.log("downloadUrl=" + downloadUrl);

    if (!wx.saveImageToPhotosAlbum) {
        wx.showModal({
            title: '提示',
            content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
        })
        return;
    }
       // 可以通过 wx.getSetting 先查询一下用户是否授权了 "scope.writePhotosAlbum" 这个 scope  
    wx.getSetting({
        success(res){
            console.log("getSetting: success");
            if (!res.authSetting['scope.writePhotosAlbum']) {
                console.log("1-没有授权《保存图片》权限");

                // 接口调用询问  
                wx.authorize({
                    scope: 'scope.writePhotosAlbum',
                    success() {
                        console.log("2-授权《保存图片》权限成功");
                        that.downloadImage(downloadUrl);
                    },
                    fail() {
                        // 用户拒绝了授权  
                        console.log("2-授权《保存图片》权限失败");
                        // 打开设置页面  
                        wx.openSetting({
                            success: function (data) {
                                console.log("openSetting: success");
                            },
                            fail: function (data) {
                                console.log("openSetting: fail");
                            }
                        });
                    }
                })
            } else {
                console.log("1-已经授权《保存图片》权限");
                that.downloadImage(downloadUrl)
            }
        },
        fail(res) {
            console.log("getSetting: fail");
            console.log(res);
        }

    })

  }, 
downloadImage: function (imageUrl) {
    // 下载文件  
    wx.downloadFile({
        url: imageUrl,
        success: function (res) {
            console.log("下载文件：success");
            console.log(res);

            // 保存图片到系统相册  
            wx.saveImageToPhotosAlbum({
                filePath: res.tempFilePath,
                success(res) {
                    console.log("保存图片：success");
                    wx.showToast({
                        title: '保存成功',
                    });
                },
                fail(res) {
                    console.log("保存图片：fail");
                    console.log(res);
                }
            })
        },
        fail: function (res) {
            console.log("下载文件：fail");
            console.log(res);
        }
    })
  },
  loadgroups:function(){
    var that=this
    wx.request({
      url: app.d.ceshiUrl + '/Api/GroupProduct/proGroup',
      method: 'post',
      data: {
        uid: app.d.userId,
        pid: that.data.pro_id,
      },
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        var data = res.data;
        if (data.status == 1) {
            that.setData({
              groups:data.data,
            });
            console.log(that.data.groups);
        } else {
          wx.showToast({
            title: res.data.err,
            duration: 2000
          });
        }
      },
      fail: function() {
        wx.showToast({
          title: '网络不给力！',
          duration: 2000
        });
      }
    });
  },
  joinGroup:function(e){
      var id=e.currentTarget.dataset.id
       wx.redirectTo({
           url: '/pages/group/detail?gid='+id,
       })
  },
});
    
       
